package com.fuyun.rpc.transmission.socket.client;

import com.fuyun.rpc.dto.RpcReq;
import com.fuyun.rpc.dto.RpcResp;
import com.fuyun.rpc.factory.SingletonFactory;
import com.fuyun.rpc.registry.ServiceDiscovery;
import com.fuyun.rpc.registry.impl.ZkServiceDiscovery;
import com.fuyun.rpc.transmission.RpcClient;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @Author fuyun。
 * @Date 2025/8/21 16:13。
 * @Description: TODO。
 **/
@Slf4j
public class SocketRpcClient implements RpcClient {
    private final ServiceDiscovery serviceDiscovery;

    public SocketRpcClient() {
        this(SingletonFactory.getInstance(ZkServiceDiscovery.class));
    }

    public SocketRpcClient(ServiceDiscovery serviceDiscovery) {
        this.serviceDiscovery = serviceDiscovery;
    }


    @Override
    public RpcResp<?> sendReq(RpcReq request) {
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(request);
        try (Socket socket = new Socket(inetSocketAddress.getAddress(), inetSocketAddress.getPort());) {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(request);
            objectOutputStream.flush();
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object object = objectInputStream.readObject();
            return (RpcResp) object;
        } catch (Exception e) {
            log.error("发送rpc 失败", e);
            throw new RuntimeException(e);
        }
    }
}
